package com.landary.parameterrplacement.service;

import com.landary.parameterrplacement.entity.Dept;
import com.landary.parameterrplacement.entity.MkDeptFdCustomProps;
import com.landary.parameterrplacement.entity.MkOrgDept;
import com.landary.parameterrplacement.entity.User;
import com.landary.parameterrplacement.utils.JDBCUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 刘欣
 * @createTime 2023/8/1 16:53
 * @description 门户与mk系统部门参数转换
 */
@Service
@Slf4j
public class DeptParamsConversionService {

    @Autowired
    private JDBCUtils jdbcUtils;


    public MkOrgDept deptParamsConversion(Dept dept, List<User> users) throws Exception {
        //直接查询数据库获取mk中所有部门
        if (dept == null) {
            throw new Exception("没有获取到门户组织部门信息！");
        }
        log.info("================================部门参数开始转换================================");
        MkOrgDept mkOrgDept = new MkOrgDept();
        //扩展字段
        MkDeptFdCustomProps mkDeptFdCustomProps = new MkDeptFdCustomProps();
        //fdId唯一标识 ==>部门编码
        if (dept.getAvicDeptCode() != null) {
            mkOrgDept.setFdId("dept:" + dept.getAvicDeptCode());
            //部门编号
            mkOrgDept.setFdNo(dept.getAvicDeptCode());
        } else {
            log.error("部门webservice接口同步的AvicDeptCode为空");
        }
        //fdname名称 ==> 部门名称
        if (dept.getAvicDeptName() != null) {
            mkOrgDept.setFdName(dept.getAvicDeptName());
            //获取部门领导
        } else {
            log.error("部门webservice接口同步的AvicDeptName为空");
        }
        //fdSourceSystem来源系统标识 ==> 固定自定义
        mkOrgDept.setFdSourceSystem("601portal");
        //组织标识
        mkOrgDept.setFdOrgType("dept");
        //判断组织状态1为有效，0位无效
        String avicDeptState = dept.getAvicDeptState();
        if (avicDeptState != null) {
            if ("1".equals(avicDeptState)) {
                mkOrgDept.setFdIsAvailable(true);
            } else {
                mkOrgDept.setFdIsAvailable(false);
            }
        } else {
            log.error("部门webservice接口同步的avicDeptState为空");
        }

        //排序号
        if (dept.getAvicSortOrder() != null) {
            mkOrgDept.setFdOrder(dept.getAvicSortOrder());
        } else {
            log.error("部门webservice接口同步的AvicSortOrder为空");
        }
        //fdParent所在部门-主部门 ==>父部门编码
        String avicParentDeptCode = dept.getAvicParentDeptCode();
        if (avicParentDeptCode != null) {
            if ("0".equals(avicParentDeptCode)) {
                mkOrgDept.setFdParent("org:" + 0);
                //同步一级部门的部门领导
                synFirstDeptLeader(dept, users, mkOrgDept);
            } else {
                mkOrgDept.setFdParent("dept:" + avicParentDeptCode);
            }
        } else {
            log.error("部门webservice接口同步的avicParentDeptCode为空");
        }
        if (dept.getAvicDeptLevel() != null) {
            mkDeptFdCustomProps.setAvicDeptLevel(dept.getAvicDeptLevel());
        } else {
            log.error("部门webservice接口同步的AvicDeptLevel为空");

        }
        if (dept.getAvicDeptRank() != null) {
            mkDeptFdCustomProps.setAvicDeptRank(dept.getAvicDeptRank());
        } else {
            log.error("部门webservice接口同步的AvicDeptRank为空");
        }
        if (dept.getAvicShowCode() != null) {
            mkDeptFdCustomProps.setAvicShowCode(dept.getAvicShowCode());
        } else {
            log.error("部门webservice接口同步的AvicShowCode为空");
        }
        if (dept.getAvicParentDeptName() != null) {
            mkDeptFdCustomProps.setAvicParentDeptName(dept.getAvicParentDeptName());
        } else {
            log.error("部门webservice接口同步的AvicParentDeptName为空");
        }

        //对主部门部门领导和部门主要领导扩展字段进行同步
        synDeptLeader(dept, users, mkOrgDept, mkDeptFdCustomProps);

        //扩展字段赋值
        mkOrgDept.setFdCustomProps(mkDeptFdCustomProps);
        log.info("================================部门参数转换结束================================");
        log.info("门户与mk系统部门参数转换" + mkOrgDept);
        return mkOrgDept;
    }

    /**
     * 同步一级部门领导（岗位为部长的为一级部门主要领导，其中部门编码为 102、215、216、的一级部门领导为主任；406的一级部门领导为董事长、409的一级部门为总经理；其余部门下没有部长岗位人的为空）
     *
     * @param dept
     * @param users
     * @param mkOrgDept
     */
    private void synFirstDeptLeader(Dept dept, List<User> users, MkOrgDept mkOrgDept) {
        log.info("=========================一级部门领导开始同步=========================");
        String avicDeptCode = dept.getAvicDeptCode();
        log.info("一级部门编码" + avicDeptCode);
        List<User> currentDeptUsers = users.stream()
                .filter(user -> Optional.ofNullable(user.getAvicDeptCode())
                        .map(code -> code.substring(0, 3).equals(avicDeptCode))
                        .orElse(false))
                .collect(Collectors.toList());
        switch (avicDeptCode) {
            //部门编码为 102、215、216、的一级部门领导为主任
            case "102":
            case "215":
            case "216":
                if (currentDeptUsers.size() > 0) {
                    for (User currentDeptUser : currentDeptUsers) {
                        if (currentDeptUser.getAvicSimpleTitle().equals("主任")) {
                            mkOrgDept.setFdThisLeader("person:" + currentDeptUser.getAvicUserAccount());
                            break;
                        } else {
                            mkOrgDept.setFdThisLeader(null);
                        }
                    }
                }
                break;
            //部门编码为406的一级部门领导为董事长
            case "406":
                if (currentDeptUsers.size() > 0) {
                    for (User currentDeptUser : currentDeptUsers) {
                        if (currentDeptUser.getAvicSimpleTitle().equals("董事长")) {
                            mkOrgDept.setFdThisLeader("person:" + currentDeptUser.getAvicUserAccount());
                            break;
                        } else {
                            mkOrgDept.setFdThisLeader(null);
                        }
                    }
                }
                break;
            //部门编码为409的一级部门为总经理
            case "409":
                if (currentDeptUsers.size() > 0) {
                    for (User currentDeptUser : currentDeptUsers) {
                        if (currentDeptUser.getAvicSimpleTitle().equals("总经理")) {
                            mkOrgDept.setFdThisLeader("person:" + currentDeptUser.getAvicUserAccount());
                            break;
                        } else {
                            mkOrgDept.setFdThisLeader(null);
                        }
                    }
                }
                break;
            //其他部门一级领导为部长，岗位没有部长的为空
            default:
                if (currentDeptUsers.size() > 0) {
                    for (User currentDeptUser : currentDeptUsers) {
                        if (currentDeptUser.getAvicSimpleTitle().equals("部长")) {
                            mkOrgDept.setFdThisLeader("person:" + currentDeptUser.getAvicUserAccount());
                            break;
                        } else {
                            mkOrgDept.setFdThisLeader(null);
                        }
                    }
                }
                break;
        }

    }

    private void synDeptLeader(Dept dept, List<User> users, MkOrgDept mkOrgDept, MkDeptFdCustomProps mkDeptFdCustomProps) {

        //通过数据库获取部门/科室领导
        Map<String, List<String>> dbDeptLeaderTypeMap = getDBDeptLeaderType();
        //部门领导
        List<String> deptTypes = dbDeptLeaderTypeMap.get("1");
        for (String deptType : deptTypes) {
            log.info("部门领导岗位" + deptType);
        }
        //科室领导
        List<String> postTypes = dbDeptLeaderTypeMap.get("2");
        for (String postType : postTypes) {
            log.info("部门科室岗位" + postType);
        }
        //通过父部门编码判断是否是部门
        if (dept.getAvicParentDeptCode() != null && "0".equals(dept.getAvicParentDeptCode())) {
            log.info("=========================部门主要领导开始同步=========================");
            String avicDeptCode = dept.getAvicDeptCode();
            log.info("部门编码" + avicDeptCode);
//            //取出主部门领导
//            List<User> filteredUsers = new ArrayList<>();
//
//            for (User user : users) {
//                if (user.getAvicDeptCode() != null && dept.getAvicDeptCode() != null && user.getAvicDeptCode().substring(0, 3).equals(avicDeptCode.substring(0, 3))) {
//                    filteredUsers.add(user);
//                    break;
//                }
//            }
//            log.info("当前" + dept.getAvicDeptName() + "的人员有：" + filteredUsers);
            //部门领导
//            for (User filteredUser : filteredUsers) {
//                if ("部长".equals(filteredUser.getAvicSimpleTitle())) {
//                    log.info(dept.getAvicDeptName() + "部门的领导为：" + filteredUser.getFullName());
//                    mkOrgDept.setFdThisLeader("person:" + filteredUser.getAvicUserAccount());
//                    break;
//                }
//            }
            //扩展字段，部门主要领导
            List<String> fdMainLeaders = new ArrayList<>();
            for (User user : users) {
                log.info("================================================================");
                if (user.getAvicDeptCode() != null && user.getAvicSimpleTitle() != null) {
                    String avicSimpleTitle = user.getAvicSimpleTitle();
                    log.info(dept.getAvicDeptName() + "的部门编码是：" + dept.getAvicDeptCode() + "," + user.getFullName() + "," + "部门编码是" + user.getAvicDeptCode());
                    log.info("部门编码的前3位" + avicDeptCode.substring(0, 3) + ",人员编码的前3位" + user.getAvicDeptCode().substring(0, 3));
                    if (avicSimpleTitle != null && avicSimpleTitle != "" && user.getAvicDeptCode() != null && user.getAvicDeptCode().substring(0, 3).equals(avicDeptCode.substring(0, 3))) {
                        log.info(dept.getAvicDeptName() + "开始同步部门领导");
                        for (String deptType : deptTypes) {
                            log.info("部门领导的岗位" + deptType);
                        }
                        log.info(user.getFullName() + "的岗位是" + avicSimpleTitle);
                        boolean isExist = deptTypes.contains(avicSimpleTitle);
                        if (isExist) {
                            log.info(dept.getAvicDeptName() + "部门主要领导：" + user.getFullName() + ",职务：" + user.getAvicSimpleTitle());
                            fdMainLeaders.add("person:" + user.getAvicUserAccount());
                        }
                    }
                } else {
                    log.error(user.getFullName() + "的部门编码或岗位为空" + user.toString());
                }
            }
            for (String fdMainLeader : fdMainLeaders) {
                log.info(dept.getAvicDeptName() + "的部门领导" + fdMainLeader);
            }
            mkDeptFdCustomProps.setFdMainLeader(fdMainLeaders);
            log.info("=========================部门主要领导同步结束=========================");
        } else {
            log.info("=========================科室主要领导开始同步=========================");
            //对各个科室的部门主要领导进行同步
            String avicDeptCode = dept.getAvicDeptCode();
            log.info("科室编码" + avicDeptCode);
            //获取当前科室的人员
            List<User> filteredUsers = new ArrayList<>();
            for (User user : users) {
                if (user.getAvicDeptCode() != null && user.getAvicDeptCode().equals(avicDeptCode)) {
                    filteredUsers.add(user);
                }
            }
            for (User filteredUser : filteredUsers) {
                log.info(dept.getAvicDeptName() + "的人员有" + filteredUser.getFullName());
            }
            List<String> fdMainLeaders = new ArrayList<>();
            for (User filteredUser : filteredUsers) {
                log.info("================================================================");
                if (filteredUser.getAvicDeptCode() != null && filteredUser.getAvicSimpleTitle() != null) {
                    String avicSimpleTitle = filteredUser.getAvicSimpleTitle();
                    log.info(dept.getAvicDeptName() + "的部门编码是：" + dept.getAvicDeptCode() + "," + filteredUser.getFullName() + "," + "部门编码是" + filteredUser.getAvicDeptCode());
                    if (avicSimpleTitle != null && avicSimpleTitle != "") {
                        log.info(dept.getAvicDeptName() + "开始同步部门领导");
                        for (String deptType : deptTypes) {
                            log.info("科室领导的岗位" + deptType);
                        }
                        log.info(filteredUser.getFullName() + "的岗位是" + avicSimpleTitle);
                        boolean isExist = postTypes.contains(avicSimpleTitle);
                        if (isExist) {
                            log.info(dept.getAvicDeptName() + "科室主要领导：" + filteredUser.getFullName() + ",职务：" + filteredUser.getAvicSimpleTitle());
                            fdMainLeaders.add("person:" + filteredUser.getAvicUserAccount());
                        }
                    }
                } else {
                    log.error(filteredUser.getFullName() + "的部门编码或岗位为空" + filteredUser.toString());
                }
            }
            for (String fdMainLeader : fdMainLeaders) {
                log.info(dept.getAvicDeptName() + "的科室领导" + fdMainLeader);
            }
            mkDeptFdCustomProps.setFdMainLeader(fdMainLeaders);
            log.info("=========================科室主要领导同步结束=========================");
        }
    }

    /**
     * 获取数据库表中部门/科室领导的主要领导岗位
     *
     * @return
     */
    public Map<String, List<String>> getDBDeptLeaderType() {
        Map<String, List<String>> deptLeaderTypeMap = new HashMap<>();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<String> deptLeaderTypes = new ArrayList<>();
        List<String> postLeaderTypes = new ArrayList<>();
        try {
            conn = jdbcUtils.getConnection();
            stmt = conn.createStatement();
            //正式环境查询部门主要领导规则
            String sql = "SELECT  FD_COL_3AYVMF,FD_COL_C504DC FROM MK_MODEL_DEPTLEADER";
            //测试环境查询部门主要领导规则
//            String sql = "SELECT  FD_COL_9G8G65,FD_COL_MJLGLH FROM MK_MODEL_DEPTLEADER";
            rs = stmt.executeQuery(sql);
            log.info("执行的sql" + sql);
            while (rs.next()) {
                //获取测试规则数据
//                String deptType = rs.getString("FD_COL_9G8G65");
//                String deptPost = rs.getString("FD_COL_MJLGLH");
                //获取正式规则数据
                String deptType = rs.getString("FD_COL_3AYVMF");
                String deptPost = rs.getString("FD_COL_C504DC");
                log.info("获取的结果集：" + deptType + "," + deptPost);
                if (deptType != null && deptPost != null) {
                    if ("1".equals(deptType)) {
                        deptLeaderTypes.add(deptPost);
                    }
                    if ("2".equals(deptType)) {
                        postLeaderTypes.add(deptPost);
                    }
                }
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            log.info(e.toString());
        } finally {
            JDBCUtils.close(conn, stmt, rs);
        }
        deptLeaderTypeMap.put("1", deptLeaderTypes);
        deptLeaderTypeMap.put("2", postLeaderTypes);
        for (Map.Entry<String, List<String>> entry : deptLeaderTypeMap.entrySet()) {
            log.info("部门/科室领导岗位对应关系" + entry.getKey() + "，值：");
            for (String value : entry.getValue()) {
                log.info(" - " + value);
            }
        }
        return deptLeaderTypeMap;
    }

}
